<template>
  <div class="chat-container">
    <div class="chat-header">
      <div class="chat-title">
        <el-icon class="chat-icon"><ChatDotRound /></el-icon>
        <span>智能对话</span>
      </div>
      <el-button size="small" @click="clearMessages" class="clear-btn">
        <el-icon><Delete /></el-icon>
        清空对话
      </el-button>
    </div>
    <div class="chat-messages" ref="messagesContainer">
      <transition-group name="message-fade">
        <div v-for="(message, index) in messages" :key="index" :class="['message', message.type]">
          <div class="message-avatar">
            <el-avatar :size="40" :icon="message.type === 'user' ? UserFilled : Service" :class="message.type === 'user' ? 'user-avatar' : 'ai-avatar'" />
          </div>
          <div class="message-bubble">
            <div class="message-content">{{ message.content }}</div>
            <div class="message-time">{{ message.time }}</div>
          </div>
        </div>
      </transition-group>
      <div v-if="isTyping" class="typing-indicator">
        <div class="typing-dot"></div>
        <div class="typing-dot"></div>
        <div class="typing-dot"></div>
      </div>
    </div>
    <div class="chat-input">
      <!-- 知识库选择区域 -->
      <div class="knowledge-selector">
        <el-select
          v-model="selectedKnowledge"
          placeholder="选择知识库（可选）"
          clearable
          class="knowledge-select"
          @change="onKnowledgeChange"
        >
          <el-option
            v-for="knowledge in knowledgeList"
            :key="knowledge.knowledgeCode"
            :label="knowledge.knowledgeName"
            :value="knowledge.knowledgeCode"
          >
            <span style="float: left">{{ knowledge.knowledgeName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ knowledge.fileCount }}个文件</span>
          </el-option>
        </el-select>
      </div>
      
      <el-input
        v-model="inputMessage"
        placeholder="请输入问题，Ctrl+Enter 快速发送..."
        :rows="3"
        type="textarea"
        resize="none"
        @keyup.enter.ctrl="sendMessage"
        class="message-textarea"
      />
      <div class="input-actions">
        <el-tooltip content="上传文件" placement="top">
          <el-button circle>
            <el-icon><Paperclip /></el-icon>
          </el-button>
        </el-tooltip>
        <el-button type="primary" @click="sendMessage" :disabled="!inputMessage.trim()" class="send-button">
          <el-icon><Position /></el-icon>
          发送
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick, onMounted } from 'vue'
import { UserFilled, Service, Position, ChatDotRound, Delete, Paperclip } from '@element-plus/icons-vue'
import { sendMessage as sendChatMessage } from '@/api/chat'
import { getKnowledgeList } from '@/api/knowledge'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/stores/auth'

// 获取认证store实例
const authStore = useAuthStore()

const inputMessage = ref('')
const messagesContainer = ref(null)
const isTyping = ref(false)

// 知识库相关数据
const knowledgeList = ref([])
const selectedKnowledge = ref('')

// 获取当前时间
const getCurrentTime = () => {
  const now = new Date()
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  return `${hours}:${minutes}`
}

// 示例消息
const messages = reactive([
  { 
    type: 'ai', 
    content: '你好！我是AI助手小甜，有什么可以帮助你的吗？',
    time: getCurrentTime()
  }
])

/**
 * 获取用户知识库列表
 */
const fetchKnowledgeList = async () => {
  try {
    const response = await getKnowledgeList({
      page: 1,
      pageSize: 100 // 获取所有知识库，假设不超过100个
    })
    if (response.code === 1 && response.data && response.data.records) {
      knowledgeList.value = response.data.records || []
      console.log('获取知识库列表成功:', knowledgeList.value)
    } else {
      console.error('获取知识库列表失败:', response.message)
      ElMessage({
        message: '获取知识库列表失败',
        type: 'error'
      })
    }
  } catch (error) {
    console.error('获取知识库列表出错:', error)
    ElMessage({
      message: '获取知识库列表出错',
      type: 'error'
    })
  }
}

/**
 * 知识库选择变化处理
 * @param {string} knowledgeCode - 选中的知识库编码
 */
const onKnowledgeChange = (knowledgeCode) => {
  console.log('选择的知识库:', knowledgeCode)
  if (knowledgeCode) {
    const selectedKnowledgeInfo = knowledgeList.value.find(k => k.knowledgeCode === knowledgeCode)
    if (selectedKnowledgeInfo) {
      console.log('选择的知识库信息:', selectedKnowledgeInfo)
    }
  }
}

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim()) return
  
  const userMessage = inputMessage.value.trim()
  
  // 添加用户消息
  messages.push({
    type: 'user',
    content: userMessage,
    time: getCurrentTime()
  })
  
  // 清空输入框
  inputMessage.value = ''
  
  // 滚动到底部
  scrollToBottom()
  
  // 显示AI正在输入状态
  isTyping.value = true
  
  // 创建AI消息对象，用于流式更新
  const aiMessage = reactive({
    type: 'ai',
    content: '',
    time: getCurrentTime()
  })
  
  // 添加AI消息到列表（初始为空内容）
  messages.push(aiMessage)
  
  try {
    // 构建请求参数
    const requestParams = {
      message: userMessage,
      chatId: authStore.userInfo?.id || 'default-chat-session' // 使用登录用户的ID作为chatId
    }
    
    // 设置知识库编码：如果用户选择了知识库则使用选择的编码，否则使用默认编码'0000'
    if (selectedKnowledge.value && typeof selectedKnowledge.value === 'string' && selectedKnowledge.value.trim() !== '') {
      requestParams.knowledgeCode = selectedKnowledge.value.trim()
      console.log('使用选择的知识库:', selectedKnowledge.value)
    } else {
      requestParams.knowledgeCode = '0000'
      console.log('未选择知识库，使用默认知识库编码: 0000')
    }
    
    // 调用后端聊天接口，使用流式处理
    await sendChatMessage(requestParams, (chunk) => {
      // 流式接收数据的回调函数，实时更新AI消息内容
      aiMessage.content += chunk
      
      // 实时滚动到底部
      nextTick(() => {
        scrollToBottom()
      })
    })

    // 流式传输完成后的处理
    console.log('AI回复完成')

  } catch (error) {
    console.error('发送消息失败:', error)
    
    // 更新AI消息为错误提示
    aiMessage.content = '抱歉，我现在无法回复您的消息，请稍后再试。'

    // 显示错误提示
    ElMessage({
      message: '发送消息失败，请稍后重试',
      type: 'error'
    })

    scrollToBottom()
  } finally {
    // 隐藏AI正在输入状态
    isTyping.value = false
  }
}

/**
 * 清空对话
 * 清空前端消息列表并调用后端清空会话记忆
 */
const clearMessages = async () => {
  try {
    // 获取API基础URL
    const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api'
    
    // 调用后端清空会话记忆接口
    const response = await fetch(`${baseURL}/user/chat/clear`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': `Bearer ${authStore.token}`
      },
      body: `chatId=${authStore.userInfo?.id || 'default-chat-session'}`
    });

    if (response.ok) {
      const result = await response.json();
      if (result.code === 200) {
        // 后端清空成功，清空前端消息列表（保留欢迎消息）
        messages.splice(1);
        console.log('会话记忆清空成功');
      } else {
        console.error('清空会话记忆失败:', result.message);
        // 即使后端失败，也清空前端消息
        messages.splice(1);
      }
    } else {
      console.error('清空会话记忆请求失败');
      // 即使后端失败，也清空前端消息
      messages.splice(1);
    }
  } catch (error) {
    console.error('清空会话记忆出错:', error);
    // 即使出错，也清空前端消息
    messages.splice(1);
  }
  scrollToBottom();
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 组件挂载时获取知识库列表并滚动到底部
onMounted(() => {
  fetchKnowledgeList()
  scrollToBottom()
})
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 120px);
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background: linear-gradient(to right, #42b983, #33a06f);
  color: white;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}

.chat-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
}

.chat-icon {
  margin-right: 8px;
  font-size: 18px;
}

.clear-btn {
  font-size: 12px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-image: url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%2342b983' fill-opacity='0.05'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E");
}

.message {
  display: flex;
  margin-bottom: 20px;
  animation: fadeIn 0.3s ease-out;
}

.message-avatar {
  margin-right: 12px;
  align-self: flex-start;
}

.user-avatar {
  background: linear-gradient(135deg, #42b983, #33a06f);
  box-shadow: 0 2px 6px rgba(66, 185, 131, 0.4);
}

.ai-avatar {
  background: linear-gradient(135deg, #409EFF, #2e88e5);
  box-shadow: 0 2px 6px rgba(64, 158, 255, 0.4);
}

.message-bubble {
  position: relative;
  max-width: 70%;
}

.message-content {
  padding: 12px 16px;
  border-radius: 18px;
  word-break: break-word;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  line-height: 1.5;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  text-align: right;
}

.user {
  flex-direction: row-reverse;
}

.user .message-avatar {
  margin-right: 0;
  margin-left: 12px;
}

.user .message-time {
  text-align: left;
}

.user .message-content {
  background-color: #e6f7ff;
  color: #0d5b97;
  border-top-right-radius: 4px;
}

.user .message-content::after {
  content: '';
  position: absolute;
  top: 14px;
  right: -8px;
  width: 0;
  height: 0;
  border-top: 8px solid transparent;
  border-left: 8px solid #e6f7ff;
  border-bottom: 8px solid transparent;
}

.ai .message-content {
  background-color: white;
  color: #333;
  border-top-left-radius: 4px;
}

.ai .message-content::after {
  content: '';
  position: absolute;
  top: 14px;
  left: -8px;
  width: 0;
  height: 0;
  border-top: 8px solid transparent;
  border-right: 8px solid white;
  border-bottom: 8px solid transparent;
}

.typing-indicator {
  display: inline-flex;
  align-items: center;
  background-color: white;
  padding: 12px 16px;
  border-radius: 18px;
  margin-left: 52px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.typing-dot {
  width: 8px;
  height: 8px;
  margin: 0 2px;
  background-color: #999;
  border-radius: 50%;
  animation: typingAnimation 1.4s infinite ease-in-out;
}

.typing-dot:nth-child(1) {
  animation-delay: 0s;
}

.typing-dot:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-dot:nth-child(3) {
  animation-delay: 0.4s;
}

/* 知识库选择器样式 */
.knowledge-selector {
  margin-bottom: 12px;
}

.knowledge-select {
  width: 100%;
  max-width: 300px;
}

.knowledge-select .el-input__inner {
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.knowledge-select .el-input__inner:hover {
  border-color: #c0c4cc;
}

.knowledge-select .el-input__inner:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 聊天输入区域 */
.chat-input {
  padding: 16px;
  background-color: white;
  border-top: 1px solid #eee;
  display: flex;
  flex-direction: column;
}

.message-textarea {
  margin-bottom: 10px;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.send-button {
  padding: 10px 20px;
  border-radius: 20px;
  transition: all 0.3s;
}

.send-button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(66, 185, 131, 0.4);
}

/* 消息动画 */
.message-fade-enter-active {
  animation: fadeIn 0.3s;
}

.message-fade-leave-active {
  animation: fadeOut 0.3s;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fadeOut {
  from {
    opacity: 1;
    transform: translateY(0);
  }
  to {
    opacity: 0;
    transform: translateY(-20px);
  }
}

@keyframes typingAnimation {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.6;
  }
  30% {
    transform: translateY(-4px);
    opacity: 1;
  }
}
</style>